package com.jrx.anytxn.param.job.partnerShare;


import com.jrx.anytxn.param.config.AnytxnBatchProperties;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.PrShareProfitTable;
import com.jrx.anytxn.param.mapper.ext.ExtPrShareProfitTableMapper;
import com.jrx.anytxn.param.service.partner.IPartnerGeneralService;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 更新分润参数表
 */
@Configuration
@EnableConfigurationProperties(AnytxnBatchProperties.class)
public class UpdateShareProfitConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(UpdateShareProfitConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Resource
    private ExtPrShareProfitTableMapper extPrShareProfitTableMapper;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private IPartnerGeneralService partnerGeneralService;

    @Bean
    public Job updateShareProfitJob() {
        return jobBuilderFactory.get("updateShareProfitJob")
                .start(updateShareProfitStep())
                .build();
    }

    @Bean
    public Step updateShareProfitStep() {
        return stepBuilderFactory.get("updateShareProfitStep")
                .tasklet(updateShareProfitTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet updateShareProfitTasklet() {
        return (stepContribution, chunkContext) -> {
            PrOrganizationTable organization =
                    organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
            Date toDay = organization.getToday();

            List<PrShareProfitTable> tableList = extPrShareProfitTableMapper.selectByNextShareDate(toDay,organization.getTenantId());
            partnerGeneralService.updateshareProfit(tableList,organization);

            logger.info("参数配置表更新完成");
            return RepeatStatus.FINISHED;
        };
    }
}
